package com.ruoyi.match.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.match.dto.LoginDto;
import com.ruoyi.match.dto.RegisterDto;
import com.ruoyi.match.entity.User;
import com.ruoyi.match.mapper.UserMapper;
import com.ruoyi.match.service.AuthService;
import com.ruoyi.match.utils.CheckMailUtils;
import com.ruoyi.match.utils.CheckPhoneUtils;
import com.ruoyi.match.utils.JwtUtils;
import com.ruoyi.match.utils.PasswordUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Author: 廖振辉
 * Date: 2022/4/27
 * Description:
 */
@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public String login(LoginDto loginDto) {
        String password = loginDto.getPassword();
        String username = loginDto.getUsername();
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
        if (user != null){
            String salt = user.getSalt();
            String encryptionPassword = PasswordUtils.getEncryptionPassword(password, salt);
            if (user.getPassword() != null && user.getPassword().equals(encryptionPassword)){
                return JwtUtils.createToken(user.getId(), null);
            }
        }
        throw new RuntimeException("用户名或密码错误");
    }

    @Override
    public void register(RegisterDto registerDto) {
        User input = new User();
        BeanUtils.copyProperties(registerDto,input);
        if (StringUtils.isEmpty(input.getUsername())) {
            throw new RuntimeException("用户名不可为空");
        }
        if (!PasswordUtils.checkPasswordLength(input.getPassword())) {
            throw new RuntimeException("密码长度需8~16位");
        }

        if (!CheckPhoneUtils.checkPhone(input.getPhone())) {
            throw new RuntimeException("手机号格式不正确");
        }
        if (!CheckMailUtils.validEmail(input.getEmail())) {
            throw new RuntimeException("邮箱格式不正确");
        }
        String gender = input.getGender();
        if ("男".equals(gender) || "女".equals(gender)){
            input.setGender("男");
        }

        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", input.getUsername()));
        if (user != null){
            throw new RuntimeException("该用户名已存在");
        }
        String encryptionSalt = PasswordUtils.getEncryptionSalt();
        String encryptionPassword = PasswordUtils.getEncryptionPassword(input.getPassword(), encryptionSalt);
        input.setPassword(encryptionPassword);
        input.setSalt(encryptionSalt);
        userMapper.insert(input);
    }
}
